<template>
  <div class="outsource-operation">
    <el-container class="layout-container">
      <!-- 头部 -->
      <el-header class="app-header">
        <div class="header-content">
          <h1 class="header-title">来访登记</h1>
        </div>
      </el-header>

      <!-- 主体内容 -->
      <el-main class="app-main">
        <div class="main-container">
          <!-- 根据状态显示不同组件 -->
          <CodeType
            v-if="isShow && !isEmpty"
            :form-data="formData"
            @get-detail="getDetail"
            @reset="reset"
          />
          <ResetInfo
            v-else-if="isShow && isEmpty"
            :company-list="ZKList"
            :type="type"
            :data="formData"
            :wxid="openid"
            :qr-object="qrObject"
            @get-detail="getDetail"
          />

          <!-- 加载状态 -->
          <div v-else class="loading-container">
            <el-skeleton :rows="6" animated />
          </div>
        </div>
      </el-main>

      <!-- 底部 -->
      <el-footer class="app-footer">
        <div class="footer-content">
          <p>&copy; 2025 企业访客登记系统</p>
        </div>
      </el-footer>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import {
  getInfoByCodeApi,
  getTokenApi,
  getZKListApi,
  getZKDetailApi,
} from "~/composables/useOutsourceOperation";
import CodeType from "~/components/outsource-operation/CodeType.vue";
import ResetInfo from "~/components/outsource-operation/ResetInfo.vue";
import type { VisitorInfo } from "~/types/api";
import { useAppStore } from "~/stores/app";

const route = useRoute();

// 响应式数据
const ZKList = ref<Array<{ QYBH: string; QYMC: string }>>([]);
const formData = ref<Partial<VisitorInfo>>({});
const wxcode = ref("");
const isEmpty = ref(true);
const isShow = ref(false);
const qrObject = ref<Record<string, string>>({});
const openid = ref("");
const type = ref("qy");

// 解析URL参数（更健壮，支持编码与缺省情况）
const parseUrlParams = (raw: string): Record<string, string> => {
  try {
    const url = raw.includes("?") ? new URL(raw) : new URL(`https://d/placeholder?${raw}`);
    const result: Record<string, string> = {};
    url.searchParams.forEach((value, key) => {
      result[key] = value;
    });
    return result;
  } catch {
    return {};
  }
};

// 统一错误提示
const showError = (msg: string) => ElMessage.error(msg || "请求失败，请重试");

// 租赁管理登录
const leasedMgntLogin = async () => {
  try {
    if (type.value === "qy") {
      await getDetail();
    } else {
      await Promise.all([getZK(), getDetail()]);
    }
  } catch (error) {
    console.error("登录失败:", error);
    showError("登录失败，请重试");
  }
};

// 获取访客详情
const getDetail = async (reset = false): Promise<void> => {
  try {
    const params =
      type.value === "qy"
        ? { CODE: openid.value, QYBH: qrObject.value.QYBH }
        : { WXID: openid.value, ...qrObject.value };

    const api = type.value === "qy" ? getInfoByCodeApi : getZKDetailApi;
    const response = await api(params);

    if (response.code === "-1") {
      showError(response.message || "获取详情失败");
      return;
    }

    isShow.value = true;

    if (!reset && response.result) {
      formData.value = response.result;

      // 检查通行证是否过期
      if (
        formData.value.YXQJSSJ &&
        new Date(formData.value.YXQJSSJ + " 23:59:59") < new Date()
      ) {
        isEmpty.value = true;
        formData.value = {};
      } else {
        isEmpty.value = false;
      }
    } else {
      isEmpty.value = true;
    }
  } catch (error) {
    console.error("获取详情失败:", error);
    showError("获取详情失败，请重试");
  }
};

// 获取租客列表
const getZK = async (): Promise<void> => {
  try {
    const response = await getZKListApi(qrObject.value);

    if (response.code === "-1") {
      showError(response.message || "获取租客列表失败");
      return;
    }

    isShow.value = true;
    ZKList.value = response.result || [];
  } catch (error) {
    console.error("获取租客列表失败:", error);
    showError("获取租客列表失败，请重试");
  }
};

// 获取token
const getToken = async (): Promise<void> => {
  try {
    const response = await getTokenApi();

    if (response.code === "-1") {
      showError(response.message || "获取token失败");
      return;
    }
    if (response.result) {
      // 这里应该设置到store中，但需要先配置store
      console.log("Token获取成功:", response.result.AJDLXX);
      const appStore = useAppStore();
      appStore.setUserToken(response.result.AJDLXX);
    }
  } catch (error) {
    console.error("获取token失败:", error);
    showError("获取token失败，请重试");
  }
};

// 重置表单
const reset = () => {
  getDetail(true);
};

// 初始化数据
const initData = () => {
  qrObject.value = {
    QYMC: route.query.QYMC as string,
  };
  type.value = qrObject.value.QYBH ? "qy" : "fd";
  processData();
};

// 处理数据
const processData = () => {
  getToken();
};

// 组件挂载
onMounted(() => {
  initData();
  leasedMgntLogin();
});
</script>

<style scoped>
.outsource-operation {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.layout-container {
  min-height: 100vh;
}

.app-header {
  background: transparent;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 2rem 0;
}

.header-content {
  text-align: center;
}

.header-title {
  font-size: 2.5rem;
  margin-bottom: 0.5rem;
  font-weight: 300;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.header-subtitle {
  font-size: 1.1rem;
  opacity: 0.9;
  margin: 0;
}

.app-main {
  padding: 2rem 0;
  background: #f5f7fa;
}

.main-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 20px;
}

.loading-container {
  padding: 2rem;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.app-footer {
  background: #303133;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 1rem 0;
}

.footer-content {
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-container {
    padding: 0 15px;
  }

  .header-title {
    font-size: 2rem;
  }

  .header-subtitle {
    font-size: 1rem;
  }

  .loading-container {
    padding: 1rem;
  }
}
</style>
